package com.example.lets;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadListener;
import com.gc.materialdesign.widgets.SnackBar;
import com.widget.CircleImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UpdateListener;

public class CompleteInfoActivity extends BaseActivity {

    private SelectPicPopupWindow selWindow;
    private Uri photoUri = null;
    private String fileName = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complete_info);
        fileName = null;

        ///
        /// gender
        ///
        final CheckBox boxFemale = (CheckBox) CompleteInfoActivity.this.findViewById(R.id.complete_info_female);
        final CheckBox boxMale = (CheckBox) CompleteInfoActivity.this.findViewById(R.id.complete_info_male);
        boxFemale.setOnClickListener(new CheckBox.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (boxMale.isChecked()) {
                    boxMale.setChecked(false);
                }
            }
        });
        boxMale.setOnClickListener(new CheckBox.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (boxFemale.isChecked()) {
                    boxFemale.setChecked(false);
                }
            }
        });

        ///
        /// toolbar
        ///
        Toolbar toolbar = (Toolbar) this.findViewById(R.id.complete_info_toolbar);
        toolbar.setTitle("完善信息");
        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (fileName == null || fileName.equals("")) {
                    Log.i("bmob", "头像不存在！");
                    new SnackBar(CompleteInfoActivity.this, "头像不存在", null, null).show();
                    return false;
                }

                String gender = (boxMale.isChecked()) ? "male" : "female";
                String userName = ((EditText) CompleteInfoActivity.this.findViewById(
                        R.id.complete_info_username)).getText().toString();
                Integer age = Integer.valueOf("0");

                if (userName == null || userName.equals("")) {
                    new SnackBar(CompleteInfoActivity.this, "请输入用户名", null, null).show();
                    return false;
                }

                if (userName.length() > 12) {
                    new SnackBar(CompleteInfoActivity.this, "用户昵称过长，请限制在12个字符以内",
                            null, null).show();
                    return false;
                }

                if (!boxMale.isChecked() && !boxFemale.isChecked()) {
                    new SnackBar(CompleteInfoActivity.this, "性别不明", null, null).show();
                    return false;
                }

                try {
                    age = Integer.parseInt(((EditText) CompleteInfoActivity.this.findViewById(
                            R.id.complete_info_age)).getText().toString());
                } catch (NumberFormatException e) {
                    new SnackBar(CompleteInfoActivity.this, "请输入正确的年龄", null, null).show();
                }

                if (age <= 0 || age >= 100) {
                    new SnackBar(CompleteInfoActivity.this, "请输入正确的年龄", null, null).show();
                    return false;
                }

                String tag1 = ((EditText) CompleteInfoActivity.this.findViewById(
                        R.id.complete_info_tag1)).getText().toString();
                String tag2 = ((EditText) CompleteInfoActivity.this.findViewById(
                        R.id.complete_info_tag2)).getText().toString();
                String tag3 = ((EditText) CompleteInfoActivity.this.findViewById(
                        R.id.complete_info_tag3)).getText().toString();
                String description = ((EditText) CompleteInfoActivity.this.findViewById(
                        R.id.complete_info_description)).getText().toString();

                completeInfo(userName, gender, age, tag1, tag2, tag3, description);
                return true;
            }
        });

        ///
        /// head image
        ///
        CircleImageView upload = (CircleImageView) this.findViewById(R.id.complete_info_portrait);
        upload.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {

                selWindow = new SelectPicPopupWindow(CompleteInfoActivity.this, new OnClickListener() {
                    // Ϊ��������ʵ�ּ�����
                    public void onClick(View v) {

                        selWindow.dismiss();

                        int id = v.getId();
                        if (id == R.id.btn_take_photo) {
                            SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
                            String filename = "Lets_Head_" + timeStampFormat.format(new Date());
                            ContentValues values = new ContentValues();
                            values.put(Media.TITLE, filename);
                            Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                            intent1.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                            startActivityForResult(intent1, 1);
                        } else if (id == R.id.btn_pick_photo) {
                            Intent intent2 = new Intent();
                            intent2.setType("image/*");
                            intent2.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent2, 2);
                        } else {
                            Log.i("bmob", "undefined button");
                            new SnackBar(CompleteInfoActivity.this, "未定义的按钮", null, null).show();
                        }
                    }
                });

                selWindow.showAtLocation(CompleteInfoActivity.this.findViewById(R.id.complete_info_portrait),
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Uri uri = null;
                    if (data != null && data.getData() != null)
                        uri = data.getData();
                    else if (photoUri != null)
                        uri = photoUri;
                    else {
                        new SnackBar(CompleteInfoActivity.this, "照取图片出错", null, null).show();
                        Log.i("bmob", "照取图片出错！");
                    }
                    cropPhoto(uri);
                }
                break;

            case 2:
                if (data != null) {
                    Uri uri = data.getData();
                    cropPhoto(uri);
                    Log.e("uri", uri.toString());
                } else {
                    Log.i("bmob", "图片不存在！");
                    new SnackBar(CompleteInfoActivity.this, "图片不存在", null, null).show();
                }
                break;

            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    Bitmap head = extras.getParcelable("data");
                    if (head != null) {
                        setPicToView(head);
                        ImageView imageView = (ImageView) findViewById(R.id.complete_info_portrait);
                        imageView.setImageBitmap(head);
                    }
                }
                break;

            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    // 将mBitmap保存在SD卡中
    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        FileOutputStream b = null;
        String path = "/sdcard/Lets/myHead/";
        File file = new File(path);
        if (!file.exists()) file.mkdirs();

        User curUser = BmobUser.getCurrentUser(this, User.class);
        fileName = path + curUser.getUsername() + "_head.jpg";
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
            Log.i("bmob", "成功写入图片文件至" + fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.i("bmob", e.getMessage());
        } finally {
            try {
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void completeInfo(String userName, String gender, Integer age, String tag1,
                              String tag2, String tag3, String description) {

        final User curUser = BmobUser.getCurrentUser(this, User.class);
        if (curUser != null) {

            Log.d("bmob", "getObjectId = " + curUser.getObjectId());
            Log.d("bmob", "getUsername = " + curUser.getUsername());
            Log.d("bmob", "getEmail = " + curUser.getEmail());

            final User newUser = new User();
            newUser.setNickname(userName);
            newUser.setAge(age);
            newUser.setGender(gender);
            newUser.setTag1(tag1);
            newUser.setTag2(tag2);
            newUser.setTag3(tag3);
            newUser.setDescription(description);

            File file = new File(fileName);
            if (!file.exists()) {
                Log.e("bmob", "头像文件不存在！");
                new SnackBar(CompleteInfoActivity.this, "头像文件不存在", null, null).show();
                return;
            }

            BmobProFile.getInstance(this).upload(fileName, new UploadListener() {

                @Override
                public void onSuccess(String fileName, String url, BmobFile file) {
                    Log.i("bmob", "文件上传成功：" + fileName + ",可访问的文件地址：" + file.getUrl());
                    newUser.setPicture(file);
                    newUser.setPicFilename(fileName);
                    newUser.update(CompleteInfoActivity.this, curUser.getObjectId(), new UpdateListener() {
                        @Override
                        public void onFailure(int arg0, String arg1) {
                            new SnackBar(CompleteInfoActivity.this, "完善失败", null, null).show();
                        }

                        @Override
                        public void onSuccess() {
                            new SnackBar(CompleteInfoActivity.this, "完善成功", null, null).show();
                            Intent intent = new Intent();
                            intent.setClass(CompleteInfoActivity.this, HomeActivity.class);
                            startActivity(intent);
                            CompleteInfoActivity.this.finish();
                        }
                    });
                }

                @Override
                public void onProgress(int progress) {
                    Log.i("bmob", "onProgress :" + progress);
                }

                @Override
                public void onError(int statuscode, String errormsg) {
                    Log.i("bmob", "文件上传失败：" + errormsg);
                }
            });
        } else {
            new SnackBar(CompleteInfoActivity.this, "还未登陆", null, null).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.complete_info, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(intent);
        return;
    }
}
